import React, { useState } from 'react';
import { Upload, Button, Form, Input, DatePicker, Card, Alert, Table, message } from 'antd';
import { UploadOutlined, InboxOutlined } from '@ant-design/icons';
import api from '../services/api';
import dayjs from 'dayjs';

const { Dragger } = Upload;

const UploadPage = () => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [result, setResult] = useState(null);

  const handleUpload = async () => {
    try {
      const values = await form.validateFields();
      
      if (fileList.length === 0) {
        message.error('请选择要上传的文件');
        return;
      }

      setUploading(true);
      setResult(null);

      const response = await api.importScores(
        fileList[0],
        values.examName,
        values.examDate.format('YYYY-MM-DD')
      );

      if (response.success) {
        message.success('导入成功');
        setResult(response.data);
        setFileList([]);
        form.resetFields();
      }
    } catch (error) {
      // 错误已在 request.js 中处理
    } finally {
      setUploading(false);
    }
  };

  const uploadProps = {
    onRemove: () => {
      setFileList([]);
    },
    beforeUpload: (file) => {
      const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
      if (!isExcel) {
        message.error('只能上传 Excel 文件（.xlsx 或 .xls）');
        return false;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error('文件大小不能超过 10MB');
        return false;
      }
      setFileList([file]);
      return false;
    },
    fileList,
    maxCount: 1
  };

  const errorColumns = [
    {
      title: '行号',
      dataIndex: 'row',
      key: 'row',
      width: 80
    },
    {
      title: '准考证号',
      dataIndex: 'studentId',
      key: 'studentId',
      width: 120
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100
    },
    {
      title: '错误原因',
      dataIndex: 'reason',
      key: 'reason'
    }
  ];

  return (
    <div>
      <Card title="上传成绩文件" style={{ marginBottom: 24 }}>
        <Alert
          message="文件格式说明"
          description={
            <div>
              <p>请上传包含以下列的 Excel 文件：</p>
              <p><strong>必填列：</strong>准考证号、姓名</p>
              <p><strong>可选列：</strong>班级、语文、数学、英语、物理、化学、生物、政治、历史、地理、总分、校次</p>
              <p>文件大小不超过 10MB，支持 .xlsx 和 .xls 格式</p>
            </div>
          }
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />

        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="examName"
            label="考试名称"
            rules={[{ required: true, message: '请输入考试名称' }]}
          >
            <Input placeholder="例如：高一第一次月考" />
          </Form.Item>

          <Form.Item
            name="examDate"
            label="考试日期"
            rules={[{ required: true, message: '请选择考试日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item label="选择文件">
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持 .xlsx 和 .xls 格式，文件大小不超过 10MB
              </p>
            </Dragger>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              onClick={handleUpload}
              loading={uploading}
              disabled={fileList.length === 0}
              icon={<UploadOutlined />}
              size="large"
            >
              {uploading ? '导入中...' : '开始导入'}
            </Button>
          </Form.Item>
        </Form>
      </Card>

      {result && (
        <Card title="导入结果">
          <Alert
            message={`导入完成：成功 ${result.successRecords} 条，失败 ${result.failedRecords} 条`}
            type={result.failedRecords === 0 ? 'success' : 'warning'}
            showIcon
            style={{ marginBottom: 16 }}
          />

          {result.errors && result.errors.length > 0 && (
            <>
              <h3>错误详情：</h3>
              <Table
                columns={errorColumns}
                dataSource={result.errors}
                rowKey={(record) => record.row}
                pagination={{ pageSize: 10 }}
                scroll={{ x: true }}
              />
            </>
          )}
        </Card>
      )}
    </div>
  );
};

export default UploadPage;
